import { useState, useEffect } from 'react'
import { Bell, BellOff, CheckCircle, X } from 'lucide-react'
import NotificationService from '../services/notificationService'

interface NotificationPermissionProps {
  onPermissionChange?: (permission: NotificationPermission) => void
  showAsCard?: boolean
  autoRequest?: boolean
}

export default function NotificationPermission({ 
  onPermissionChange, 
  showAsCard = true,
  autoRequest = false 
}: NotificationPermissionProps) {
  const [permission, setPermission] = useState<NotificationPermission>('default')
  const [isRequesting, setIsRequesting] = useState(false)
  const [showPrompt, setShowPrompt] = useState(false)
  const [dismissed, setDismissed] = useState(false)

  useEffect(() => {
    const notificationService = NotificationService.getInstance()
    
    // 检查当前权限状态
    const currentPermission = notificationService.getPermissionStatus()
    setPermission(currentPermission)

    // 检查是否已经忽略过提示
    const wasDismissed = localStorage.getItem('aide_notification_prompt_dismissed') === 'true'
    setDismissed(wasDismissed)

    // 如果权限未授予且未被忽略，显示提示
    if (currentPermission === 'default' && !wasDismissed) {
      setShowPrompt(true)
    }

    // 如果设置了自动请求权限
    if (autoRequest && currentPermission === 'default' && !wasDismissed) {
      handleRequestPermission()
    }
  }, [autoRequest])

  const handleRequestPermission = async () => {
    setIsRequesting(true)
    const notificationService = NotificationService.getInstance()
    
    try {
      const newPermission = await notificationService.requestPermission()
      setPermission(newPermission)
      setShowPrompt(false)
      
      if (onPermissionChange) {
        onPermissionChange(newPermission)
      }

      // 如果权限被授予，发送测试通知
      if (newPermission === 'granted') {
        setTimeout(() => {
          notificationService.showNotification('🎉 通知已启用', {
            body: 'AIDE 现在可以发送任务提醒通知了',
            tag: 'permission-granted'
          })
        }, 1000)
      }
    } catch (error) {
      console.error('请求通知权限失败:', error)
    } finally {
      setIsRequesting(false)
    }
  }

  const handleDismiss = () => {
    setShowPrompt(false)
    setDismissed(true)
    localStorage.setItem('aide_notification_prompt_dismissed', 'true')
  }



  const getPermissionIcon = () => {
    switch (permission) {
      case 'granted':
        return <CheckCircle size={20} className="text-green-600" />
      case 'denied':
        return <BellOff size={20} className="text-red-600" />
      default:
        return <Bell size={20} className="text-orange-600" />
    }
  }

  const getPermissionText = () => {
    switch (permission) {
      case 'granted':
        return '通知权限已授予'
      case 'denied':
        return '通知权限已拒绝'
      default:
        return '需要通知权限'
    }
  }

  const getPermissionDescription = () => {
    switch (permission) {
      case 'granted':
        return 'AIDE 可以发送任务提醒通知'
      case 'denied':
        return '无法发送通知，请在浏览器设置中手动启用'
      default:
        return '允许 AIDE 发送任务到期提醒'
    }
  }

  // 如果已经忽略且不显示提示，则不渲染
  if (dismissed && !showPrompt && permission !== 'granted') {
    return null
  }

  // 如果权限已授予且不是卡片模式，则不显示
  if (permission === 'granted' && !showAsCard) {
    return null
  }

  const content = (
    <div className={`flex items-center gap-3 ${showAsCard ? 'p-4' : 'p-3'}`}>
      <div className="flex-shrink-0">
        {getPermissionIcon()}
      </div>
      
      <div className="flex-1 min-w-0">
        <div className="font-medium text-theme-text">
          {getPermissionText()}
        </div>
        <div className="text-sm text-theme-text-secondary mt-1">
          {getPermissionDescription()}
        </div>
      </div>

      <div className="flex items-center gap-2">
        {permission === 'default' && (
          <>
            <button
              onClick={handleRequestPermission}
              disabled={isRequesting}
              className={`px-3 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 ${
                isRequesting ? 'cursor-not-allowed' : ''
              }`}
            >
              {isRequesting ? '请求中...' : '启用'}
            </button>
            
            <button
              onClick={handleDismiss}
              className="p-2 text-slate-400 hover:text-theme-text-secondary hover:bg-theme-bg-tertiary rounded-lg transition-colors"
              title="暂时忽略"
            >
              <X size={16} />
            </button>
          </>
        )}

        {permission === 'denied' && (
          <button
            onClick={() => {
              alert('请在浏览器地址栏左侧的锁图标中，或在浏览器设置中手动启用通知权限')
            }}
            className="px-3 py-2 bg-theme-bg-tertiary text-theme-text-secondary text-sm font-medium rounded-lg hover:bg-slate-200 transition-colors"
          >
            查看帮助
          </button>
        )}

        {permission === 'granted' && showAsCard && (
          <button
            onClick={async () => {
              // 发送测试通知
              await NotificationService.getInstance().showNotification('🔔 测试通知', {
                body: '这是一个测试通知，确认通知功能正常工作',
                tag: 'test-notification'
              })
            }}
            className="px-3 py-2 bg-green-100 text-green-700 text-sm font-medium rounded-lg hover:bg-green-200 transition-colors"
          >
            测试通知
          </button>
        )}
      </div>
    </div>
  )

  if (!showAsCard) {
    return (
      <div className="bg-orange-50 border border-orange-200 rounded-lg">
        {content}
      </div>
    )
  }

  return (
    <div className={`bg-theme-bg rounded-2xl border shadow-sm ${
      permission === 'granted' 
        ? 'border-green-200' 
        : permission === 'denied' 
          ? 'border-red-200' 
          : 'border-orange-200'
    }`}>
      {content}
    </div>
  )
}

// 简化的权限状态指示器
export function NotificationStatus() {
  const [permission, setPermission] = useState<NotificationPermission>('default')

  useEffect(() => {
    const notificationService = NotificationService.getInstance()
    const currentPermission = notificationService.getPermissionStatus()
    setPermission(currentPermission)
    
    // 监听权限变化
    const checkPermission = () => {
      const newPermission = notificationService.getPermissionStatus()
      if (newPermission !== permission) {
        setPermission(newPermission)
      }
    }

    const interval = setInterval(checkPermission, 5000)
    return () => clearInterval(interval)
  }, [permission])

  const getStatusColor = () => {
    switch (permission) {
      case 'granted':
        return 'text-green-600'
      case 'denied':
        return 'text-red-600'
      default:
        return 'text-orange-600'
    }
  }

  return (
    <div className={`inline-flex items-center gap-1 ${getStatusColor()}`}>
      {permission === 'granted' ? (
        <Bell size={16} />
      ) : (
        <BellOff size={16} />
      )}
      <span className="text-xs">
        {permission === 'granted' ? '已启用' : permission === 'denied' ? '已拒绝' : '未启用'}
      </span>
    </div>
  )
}
